package com.mezizy.ifanmerchant;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.Filter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.mezizy.ifanmerchant.customui.MyListView;
import com.mezizy.ifanmerchant.global.Config;
import com.mezizy.ifanmerchant.global.GetNewOrderService;
import com.mezizy.ifanmerchant.global.Global;
import com.mezizy.ifanmerchant.global.com.mezizy.ifaner.web.data.Dish;
import com.mezizy.ifanmerchant.global.com.mezizy.ifaner.web.data.Order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;


public class NewOrderTab extends Fragment {

    static MyListView listViewNewOrder;
    static SimpleAdapter simpleAdapter;
    static ImageView btnNewOrderPop;
    RadioGroup rdgNewOrderFilter;


    private static final int RDB_STATE_ORDER_ALL = 0;
    private static final int RDB_STATE_ORDER_NOT_CONFIRM = 1;
    private static final int RDB_STATE_ORDER_PROCESS = 2;

    static int newOrderRdbState = RDB_STATE_ORDER_ALL;


    public static Handler handler = new Handler();
    private BroadcastReceiver MsgReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
//            Toast.makeText(getActivity(), "新訂單已加入", Toast.LENGTH_LONG).show();
            Global.showToast("新訂單");
            Global.soundRing();
//            new NewOrderAsync().execute();
            if (GetNewOrderService.newOrderNum == 1) {
                //如果没有东西就直接显示出来
                new NewOrderAsync().execute();
            } else if (btnNewOrderPop.getVisibility() != View.VISIBLE) {
                //如果没有新订单pop提示没有显示，就显示动画
                final Animation translateAnimation = new TranslateAnimation(0, 0, -100, 0);
                translateAnimation.setDuration(500);
                btnNewOrderPop.setVisibility(View.VISIBLE);
                btnNewOrderPop.setAnimation(translateAnimation);
                btnNewOrderPop.startAnimation(translateAnimation);
            } else {
                Animation rotateAnimation = new RotateAnimation(0f, 360f, 0.5f, 0.5f);
                rotateAnimation.setDuration(500);
                btnNewOrderPop.setAnimation(rotateAnimation);
                btnNewOrderPop.startAnimation(rotateAnimation);
            }

        }
    };

    @Override
    public void onResume() {
        super.onResume();
//        new NewOrderAsync().execute();
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Config.ACTION_NEW_ORDER);
        getActivity().registerReceiver(MsgReceiver, intentFilter);// 注册接受消息广播

//        new NewOrderAsync().execute();

    }

    public static void startAsync() {
        new NewOrderAsync().execute();
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            getActivity().unregisterReceiver(MsgReceiver);// 注册接受消息广播
        }catch (Exception e){
            e.printStackTrace();
            Log.i("NewOrder.Pause","沒有註冊消息廣播");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_new_order, container, false);

        ((RadioButton) view.findViewById(R.id.rdbNewOrderAll)).setChecked(true);
        rdgNewOrderFilter = (RadioGroup) view.findViewById(R.id.rdgNewOrderFilter);
        rdgNewOrderFilter.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rdbNewOrderAll:
                        newOrderRdbState = RDB_STATE_ORDER_ALL;
                        break;
                    case R.id.rdbNewOrderNotConfirm:
                        newOrderRdbState = RDB_STATE_ORDER_NOT_CONFIRM;
                        break;
                    case R.id.rdbNewOrderProcess:
                        newOrderRdbState = RDB_STATE_ORDER_PROCESS;
                        break;

                }
                new NewOrderAsync().execute();
            }
        });

        btnNewOrderPop = (ImageView) view.findViewById(R.id.btnNewOrderPop);
        btnNewOrderPop.setVisibility(View.INVISIBLE);
        btnNewOrderPop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Animation translateAnimation = new TranslateAnimation(0, 0, 0, -100);
                translateAnimation.setDuration(200);
                btnNewOrderPop.setVisibility(View.VISIBLE);
                btnNewOrderPop.setAnimation(translateAnimation);
                btnNewOrderPop.startAnimation(translateAnimation);
                translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        btnNewOrderPop.setVisibility(View.INVISIBLE);
                        new NewOrderAsync().execute();

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });

            }
        });

        listViewNewOrder = (MyListView) view.findViewById(R.id.listViewNewOrder);
        listViewNewOrder.setOnRefreshListener(new MyListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new NewOrderAsync().execute();

            }
        });
//        simpleAdapter = new NewOrderAdapter(this.getActivity(), getData(), R.layout.list_new_order, new String[]{"txtOrderNum", "txtOrderDate", "txtName", "txtAddress", "txtTotalPrice", "txtRemark"}, new int[]{R.id.txtOrderNum, R.id.txtOrderDate, R.id.txtName, R.id.txtAddress, R.id.txtTotalPrice, R.id.txtRemark});
//
//        listViewNewOrder.setAdapter(simpleAdapter);
        startAsync();

        return view;
    }

    private static LinearLayout orderAdapter(LinearLayout parent, String orderId) {

        List<Map<String, Object>> dataOrder = getDataOrder(orderId);


        TextView txtOrderListDishName, txtOrderListDishQuantity, txtOrderListDishPrice;


        parent.removeAllViews();

        for (Map<String, Object> stringObjectMap : dataOrder) {
            View child = View.inflate(MainActivity.getInstance(), R.layout.list_order_list, null);
            txtOrderListDishName = (TextView) child.findViewById(R.id.txtOrderListDishName);
            txtOrderListDishQuantity = (TextView) child.findViewById(R.id.txtOrderListDishQuantity);
            txtOrderListDishPrice = (TextView) child.findViewById(R.id.txtOrderListDishPrice);

            txtOrderListDishName.setText((String) stringObjectMap.get("txtOrderListDishName"));
            txtOrderListDishQuantity.setText((String) stringObjectMap.get("txtOrderListDishQuantity"));
            txtOrderListDishPrice.setText((String) stringObjectMap.get("txtOrderListDishPrice"));

            parent.addView(child);

        }

        return parent;


        // , , new String[]{"txtOrderListDishName", "txtOrderListDishQuantity", "txtOrderListDishPrice"}, new int[]{R.id.txtOrderListDishName, R.id.txtOrderListDishQuantity, R.id.txtOrderListDishPrice
    }

    public static class NewOrderAdapter extends SimpleAdapter {

        public NewOrderAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            final Map<String, Object> map = (Map<String, Object>) getItem(position);
            final String orderId = (String) map.get("txtOrderNum");
//            NotScrollableListView listViewOrder = (NotScrollableListView) view.findViewById(R.id.listViewOrder);
//            SimpleAdapter orderListAdapter = new SimpleAdapter(NewOrderTab.this.getActivity(), getDataOrder(orderId), R.layout.list_order_list, new String[]{"txtOrderListDishName", "txtOrderListDishQuantity", "txtOrderListDishPrice"}, new int[]{R.id.txtOrderListDishName, R.id.txtOrderListDishQuantity, R.id.txtOrderListDishPrice});
//            listViewOrder.setAdapter(orderListAdapter);
            LinearLayout linearOrders = (LinearLayout) view.findViewById(R.id.linearOrders);

            orderAdapter(linearOrders, orderId);
            ((Button) view.findViewById(R.id.btnIgnore)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                     Global.showProgress(MainActivity.getInstance(), "正在更改訂單狀態");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            int state=Global.getState(orderId);
                            if (state==Config.STATE_NOT_CONFIRM){
                                if (Global.setState(orderId, Config.STATE_CANCEL)){
                                    Global.showToast("訂單忽略成功",MainActivity.getInstance());
                                }else{
                                    Global.showToast("網路錯誤",MainActivity.getInstance());

                                }

                                MainActivity.getInstance().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        new NewOrderAsync().execute();
                                    }
                                });
                            }else {
                                Global.showToast("不可忽略",MainActivity.getInstance());
                            }
                            Global.dismissProgress();
                        }
                    }).start();
                }
            });


            final Button btnNewOrderConfirm = ((Button) view.findViewById(R.id.btnConfirm));

            int state = ((int) ((Map<String, Object>) getItem(position)).get("orderState"));
            btnNewOrderConfirm.setText(Global.getButtonStateS(state));

            btnNewOrderConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Global.showToast("here!");
//                    String test_order_num = "123456";
                    Global.showProgress(MainActivity.getInstance(), "正在更改訂單狀態");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            int state = Global.getState(orderId);
                            switch (state) {
                                case Config.STATE_NOT_CONFIRM: //如果未确认订单，则确认，并更改button提示
                                    if (Global.setState(orderId, Config.STATE_CONFIRMED)) {
                                        //TODO 订单状态更改 未确认-确认
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Global.showToast("已確認訂單");
                                                map.put("orderState", Config.STATE_CONFIRMED);
//                                                btnNewOrderConfirm.setText("已完成，去通知買家");

                                            }
                                        });


                                    } else {
                                        Global.showToast("發生錯誤", MainActivity.getInstance());
                                    }

                                    break;

                                case Config.STATE_CONFIRMED://如果已经确认，则状态变为已经完成，并修改提示
                                    if (Global.setState(orderId, Config.STATE_FINISHED_NOT_PAY)) {
                                        //TODO 订单状态更改 确认-已经完成（未收款）
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Global.showToast("狀態已更改");

                                                map.put("orderState", Config.STATE_FINISHED_NOT_PAY);
//                                                btnNewOrderConfirm.setText("确认已收款");
                                            }
                                        });


                                    } else {
                                        Global.showToast("發生錯誤", MainActivity.getInstance());
                                    }

                                    break;
                                case Config.STATE_FINISHED_NOT_PAY: //如果已经完成，并且收款成功
                                    if (Global.setState(orderId, Config.STATE_FINISHED_PAID)) {
                                        //TODO 订单状态更改 已经完成（未收款）-已经完成

                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Global.showToast("已確認收款");

                                                map.put("orderState", Config.STATE_FINISHED_PAID);
//                                                btnNewOrderConfirm.setText("订单完成");
//                                                newOrderDataList.remove(getItem(position));
//                                                new NewOrderAsync().execute();

                                            }
                                        });

                                    } else {
                                        Global.showToast("發生錯誤", MainActivity.getInstance());
                                    }
                                    break;
                            }
                            MainActivity.getInstance().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new NewOrderAsync().execute();
                                    notifyDataSetChanged();
                                    Global.dismissProgress();
                                }
                            });
                        }
                    }).start();


                }
            });


            return view;
        }
    }


    public static List<Map<String, Object>> getDataOrder(String orderId) {
        List<Map<String, Object>> list = new ArrayList<>();
        Order order = Global.orderMap.get(orderId);
        if (order == null) {
            return list;
        }
        List<Dish> listDish = order.getDishList();
        for (Dish dish : listDish) {
            Map<String, Object> map = new HashMap<>();
            //TODO 修改成直接得到Name
            map.put("txtOrderListDishName", Global.getDishNameById(dish.getDishesId()));
            //TODO 修改Quantity
            map.put("txtOrderListDishQuantity", "×" + dish.getCartQuantity());
            map.put("txtOrderListDishPrice", "NT " + dish.getTotal());
            list.add(map);
        }


        return list;
    }


    public static class NewOrderAsync extends AsyncTask<List<Order>, List<Order>, List<Order>> {

        @Override
        protected void onPostExecute(List<Order> orderList) {
            List<Map<String, Object>> newOrderDataList;

            newOrderDataList = new LinkedList<>();
            //TODO  新订单 适配
            int newOrderNum = 0;
            for (Order order : orderList) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("txtOrderNum", order.getTradeId());
                map.put("txtOrderDate", order.getCreateTime());
                map.put("txtName", order.getCusName());
                map.put("txtAddress", order.getDeliverPlace());
                map.put("txtTotalPrice", "NT " + order.getAmount());
                map.put("txtRemark", order.getRemarks());
                map.put("orderState", order.getTradeState());//TODO STATE
                int orderState = order.getTradeState();
                if (orderState == Config.STATE_NOT_CONFIRM) newOrderNum++;

                //这边对显示出的新订单做筛选
                switch (newOrderRdbState) {
                    case RDB_STATE_ORDER_ALL:
                        if (orderState == Config.STATE_CANCEL) continue;
                        break;
                    case RDB_STATE_ORDER_NOT_CONFIRM:
                        if (orderState != Config.STATE_NOT_CONFIRM) continue;
                        break;
                    case RDB_STATE_ORDER_PROCESS:
                        if (orderState == Config.STATE_CANCEL || orderState == Config.STATE_NOT_CONFIRM)
                            continue;
                        break;

                }
                newOrderDataList.add(map);
            }

            //更新Server中的新訂單數量
            GetNewOrderService.newOrderNum = newOrderNum;

            //订单的菜单
            simpleAdapter = new NewOrderAdapter(MainActivity.getInstance(), newOrderDataList, R.layout.list_new_order, new String[]{"txtOrderNum", "txtOrderDate", "txtName", "txtAddress", "txtTotalPrice", "txtRemark"}, new int[]{R.id.txtOrderNum, R.id.txtOrderDate, R.id.txtName, R.id.txtAddress, R.id.txtTotalPrice, R.id.txtRemark});

            listViewNewOrder.onRefreshComplete();
            if (btnNewOrderPop.getVisibility() == View.VISIBLE) {
                final Animation translateAnimation = new TranslateAnimation(0, 0, 0, -100);
                translateAnimation.setDuration(200);
                btnNewOrderPop.setAnimation(translateAnimation);
                btnNewOrderPop.startAnimation(translateAnimation);
                translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        btnNewOrderPop.setVisibility(View.INVISIBLE);
                        listViewNewOrder.setAdapter(simpleAdapter);

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });


            } else if (btnNewOrderPop.getVisibility() == View.INVISIBLE) {
                listViewNewOrder.setAdapter(simpleAdapter);

            }
            Global.dismissProgress();

            if (newOrderNum != 0) {
                MainActivity.getInstance().findViewById(R.id.txtNoNewOrders).setVisibility(View.INVISIBLE);
            } else {
                MainActivity.getInstance().findViewById(R.id.txtNoNewOrders).setVisibility(View.VISIBLE);

            }

            super.onPostExecute(orderList);
        }

        @Override
        protected List<Order> doInBackground(List<Order>... params) {
            Global.showProgress(MainActivity.getInstance(), "加载新订单中");

            Global.getDishMapM();

            LinkedList<Order> list = new LinkedList<>();

            LinkedHashMap<String, Order> map = Global.getOrderListMerchant();
            try {

                for (Map.Entry<String, Order> entry : map.entrySet()) {
                    Order order = entry.getValue();
                    list.add(order);
                }
            } catch (NullPointerException e) {
                Global.showToast("網路連線錯誤", MainActivity.getInstance());
            }

            return list;
        }
    }

}

